﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using System.Reflection;
using BrainTechLLC.ThreadSafeObjects;

namespace BrainTechLLC
{
	[Serializable, AttributeUsage(AttributeTargets.Property)]
	public class PropertyChangedActionAttribute : Attribute, IReadableAttribute
	{
		public string PropertyNameHoldingForeignClass { get; set; }
		public string PropertyNameInForeignClass { get; set; }

		public string MethodName { get; set; }
		public object Value { get { return MethodName; } }

		public PropertyChangedActionAttribute(string propertyNameHoldingForeignClass, string propertyNameInForeignClass)
		{
			PropertyNameInForeignClass = propertyNameInForeignClass;
			PropertyNameHoldingForeignClass = propertyNameHoldingForeignClass;
		}

		public PropertyChangedActionAttribute(string methodName)
		{
			MethodName = methodName;
		}

		public void SetOnForeignClass(Type t, object thisObject, object newVal)
		{
			TypeAndProperties propLookup = t.GetTypeAndProperties();
			PropInfo propInfo = propLookup.Lookup[PropertyNameHoldingForeignClass];
			object foreignClass = propInfo.GetValue(thisObject);

			Type foreignType = foreignClass.GetType();
			TypeAndProperties propLookup2 = foreignType.GetTypeAndProperties();
			PropInfo propInfo2 = propLookup2.Lookup[PropertyNameInForeignClass];
			propInfo2.SetValue(foreignClass, newVal);
		}

		public MethodInfo GetMethod(Type t)
		{
			if (string.IsNullOrEmpty(MethodName)) 
				return null;

			return Lookups.GeneralLookup.Get(t.DotMethodName(MethodName), v => t.GetMethod(MethodName));
		}
	}
}

